package com.example.ai.utils;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class HttpUtils {

    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .build();

    public static String executePost(String url, String jsonBody, Map<String, String> headers) {
        try {
            MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
            RequestBody body = RequestBody.create(jsonBody, mediaType);

            Request.Builder requestBuilder = new Request.Builder()
                    .url(url)
                    .post(body);

            // 添加请求头
            if (headers != null) {
                headers.forEach(requestBuilder::addHeader);
            }

            Request request = requestBuilder.build();
            
            log.debug("Sending POST request to {}", url);
            Response response = client.newCall(request).execute();
            
            if (!response.isSuccessful()) {
                String errorBody = response.body() != null ? response.body().string() : "No error body";
                log.error("HTTP request failed: {} - {}", response.code(), errorBody);
                throw new RuntimeException("HTTP request failed with status: " + response.code());
            }

            String responseBody = response.body() != null ? response.body().string() : "";
            log.debug("Received response: {}", responseBody);
            return responseBody;

        } catch (IOException e) {
            log.error("Error executing HTTP request", e);
            throw new RuntimeException("Failed to execute HTTP request", e);
        }
    }
} 